//
// Created by Administrator on 2023/3/17.
//

#include "e_poller.h"
#include "log/logger_main.h"
e_poller::e_poller() : root_fd(epoll_create1(EPOLL_CLOEXEC)) {
    this->container.resize(32);
    LOG_INFO("epoll 创建成功..");
}

e_poller::~e_poller() {

    close(this->root_fd);
}

bool e_poller::add_fd(int fd, u_int32_t event) {

    if (fd <= 0 || root_fd < 0) {
        LOG_ERROR("add_fd error {},root_fd{}", fd, root_fd);
        return false;
    }

    struct epoll_event ev={0};
    ev.data.fd=fd;
    ev.events=(event|e_poller::model);
    LOG_INFO("add_fd==>{}",fd);
    //添加成功返回0
    return epoll_ctl(root_fd,EPOLL_CTL_ADD,fd,&ev)==0;

}

bool e_poller::update_fd(int fd, u_int32_t event) {
    if (fd<0||root_fd<0)
    {
        LOG_ERROR("up_fd error {},root_fd{}",fd,root_fd);
        return false;
    }
    struct epoll_event ev={0};
    ev.data.fd=fd;
    ev.events=(event|e_poller::model);
    LOG_INFO("up_fd==>{}",fd);
    return epoll_ctl(root_fd,EPOLL_CTL_MOD,fd,&ev);

}

bool e_poller::del_fd(int fd){
    if (fd<0||root_fd<0)
    {
        LOG_ERROR("del_fd error {},root_fd{}",fd,root_fd);
        return false;
    }

    LOG_INFO("del_fd==>{}",fd);
    return epoll_ctl(root_fd,EPOLL_CTL_DEL,fd, nullptr);

}

int e_poller::epoll_wait(int time) {

    //将就绪事件拷贝到缓冲区
    int ret=::epoll_wait(root_fd,&(*container.begin()),(container.size()),time);

    if (ret==container.size())
        container.reserve((container.size()<<1));//按照1.5被速度增长 没有缩减判断

        return ret;

}

epoll_event e_poller::operator[](const unsigned long long int index) {
    return this->container[index];
}

e_poller &e_poller::get_instance() {
   static e_poller e;
    return e;
}

bool e_poller::add_fd_ori(int fd, u_int32_t event) {
    if (fd<0||root_fd<0)
    {
        LOG_ERROR("add_fd error {},root_fd{}",fd,root_fd);
        return false;
    }

    struct epoll_event ev={0};
    ev.data.fd=fd;
    ev.events=(event);
    LOG_INFO("add_fd==>{}",fd);
    //添加成功返回0
    return epoll_ctl(root_fd,EPOLL_CTL_ADD,fd,&ev)==0;
}

